package com.appspot.categoryeditor.service;

import java.util.List;

import org.slim3.datastore.Datastore;

import com.appspot.categoryeditor.meta.CategoryMeta;
import com.appspot.categoryeditor.meta.FolderMeta;
import com.appspot.categoryeditor.meta.UserMeta;
import com.appspot.categoryeditor.model.Category;
import com.appspot.categoryeditor.model.Folder;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

public class CategoryService {

	final static UserMeta userMeta = UserMeta.get();
	final static FolderMeta FOLDER_META = FolderMeta.get();
	final static CategoryMeta categoryMeta = CategoryMeta.get();

	/**
	 * @param userid
	 * @param categoryId
	 * @return 
	 */
	public Category getCategory(String userid, String categoryId) {
		
		Key userKey = Datastore.createKey(userMeta, userid);
		Key categoryKey = Datastore.createKey(userKey, categoryMeta, categoryId);

		return Datastore.query(categoryMeta, userKey).filter(
				categoryMeta.id.equal(categoryKey)).asSingle();
	}
	
	public boolean checkCategoryExist(String userid){
		Key userKey = Datastore.createKey(userMeta, userid);
		return Datastore.query(categoryMeta, userKey).count() > 0;
	}
	
	

	public List<Folder> getCategoryFolders(String userid) {
		Key key = Datastore.createKey(userMeta, userid);
		List<Folder> foldersModel = Datastore
				.query(FOLDER_META, key)
				.sort(FOLDER_META.order.asc)
				.asList();
		return foldersModel;
	}

	public <E> void put(Transaction tx, E model){
		Datastore.put(tx, model);
	}
	
	public <E> void put(Transaction tx, List<E> models) {
		Datastore.put(tx, models);
	}

	/**
	 * 配下のカテゴリも削除
	 * 
	 * @param tx
	 * @param categoryFolders
	 */
	public void deleteCategoryFolders(Transaction tx,
			List<Folder> categoryFolders) {
		for (Folder folder : categoryFolders) {
			for (Category category : folder.getCategoriesRefs().getModelList()) {
				Datastore.delete( tx, category.getId());
			}
			Datastore.delete(tx, folder.getId());
		}
	}

	public  void delete(Transaction tx, Category category) {
		Datastore.delete( tx, category.getId());
	}

	
	

}
